package com.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.base.BasePageReq;
import com.base.BasePageRes;
import com.base.BaseServiceImpl;
import com.entity.Collection;
import com.exception.ServiceException;
import com.repository.CollectionRepository;
import com.req.CollectionReq;
import com.res.CollectionRes;
import com.service.CollectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class CollectionServiceImpl extends BaseServiceImpl<CollectionReq,CollectionRes, CollectionRepository, Collection> implements CollectionService {
    @Autowired
    private CollectionRepository collectionRepository;
    @Override
    public CollectionRes saveCollection(CollectionReq req) {
        return this.handle(req);
    }

    @Override
    public CollectionRes del(CollectionReq collectionReq) {
        QueryWrapper<Collection> wrapper = new QueryWrapper<>();
        wrapper.lambda().and(Wrapper->Wrapper.eq(Collection::getUserId,collectionReq.getUserId()).eq(Collection::getArticalId,collectionReq.getArticalId()));
        List<Collection> collections = this.list(wrapper);
        for (Collection collection : collections) {
            collectionReq.setId(collection.getId());
            super.del(collectionReq);
        }

        return null;
    }

    @Override
    public CollectionRes query(CollectionReq collectionReq) {
        QueryWrapper<Collection> wrapper = new QueryWrapper<>();
        wrapper.lambda().and(Wrapper->Wrapper.eq(Collection::getUserId,collectionReq.getUserId()).eq(Collection::getArticalId,collectionReq.getArticalId()));
        Collection collection = this.getOne(wrapper);
        CollectionRes collectionRes = new CollectionRes();
        BeanUtil.copyProperties(collection,collectionRes);
        return collectionRes;
    }

    @Override
    public BasePageRes queryPage(BasePageReq pageReq) {
        if (StringUtils.isEmpty(pageReq.getPage())) {
            throw new ServiceException("请传入page");
        }
        if (StringUtils.isEmpty(pageReq.getSize())) {
            throw new ServiceException("请传入size");
        }
        if(!StringUtils.isEmpty(pageReq.getDes())) {
            pageReq.setDes("%" + pageReq.getDes() + "%");
        }
        Page<CollectionRes> pages = new Page<>(pageReq.getPage(), pageReq.getSize());
        IPage<CollectionRes> collectionResIPage = collectionRepository.searchPage(pages, pageReq);
        BasePageRes basePageRes = this.convertIpage(collectionResIPage, new CollectionRes());

        return basePageRes;
    }
}
